package com.xiaohudie.aop;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.xiaohudie.pojo.MyThreadLocal;
import com.xiaohudie.pojo.User;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author xiao hu die
 * @Date 2022/3/3 17:23
 * @Version 1.0
 */
/**全局拦截器
 * 目的是用户无论走到那个页面都是可以刷新token的*/
public class GlobalInterception implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public GlobalInterception(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**获取token*/
        String token = request.getHeader("authorization");
        if (StrUtil.isBlank(token)){
            return true;
        }
        /**从redis中获取user*/
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(token);
       /**判断用户是否存在*/
       if (userMap.isEmpty()){
           return true;
       }
        /**将userMap转换为user对象*/
        User user = BeanUtil.fillBeanWithMap(userMap,new User(),false);
        /**关键代码将user放入ThreadLocal中*/
        MyThreadLocal.set(user);
        /**刷新token有效期
         * 没有操作之后就需要重新登录*/
        stringRedisTemplate.expire(token,200000, TimeUnit.MILLISECONDS);
        /**return true 就是放出这个请求*/
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        /**避免内存泄漏就是完成请求之后删除这个用户*/
        MyThreadLocal.removeUser();
    }
}
